import {Continer} from "../continer";
import {EVENT_TYPES} from "../var";

export class Area extends Continer {
  constructor() {
    super();
    // 1.创建cavans：大小100%
    this.copyCanvas = document.createElement('canvas');
    this.copyCtx = this.copyCanvas.getContext('2d');
    this.copyCanvas.classList.add('draw-freeBox-item');
    this.copyCanvas.setAttribute('eventType', EVENT_TYPES.moveEvenType);
  }

  // 设置容器清晰度
  setCopyCanvasSize() {
    this.copyCanvas.width = this.continerWidth * this.option.scale;
    this.copyCanvas.height = this.continerHeight * this.option.scale;
    // this.copyCanvas.width = (this.continerWidth - 2 ) * this.option.scale;
    // this.copyCanvas.height = (this.continerHeight - 2) * this.option.scale;
  }

  // 容器创建时
  created(img) {
    this.continer.innerHTML = '';
    this.img = img || this.copyCanvas;
    if (!img) {
      this.setCopyCanvasSize();
      this.continer.appendChild(this.img);
      this.cut2CopyCtx();
    } else {
      this.img.classList.add('draw-parentSize');
      this.continer.appendChild(this.img);
    }
  }

  // 容器销毁时
  beforeDestroy() {
    this.paste();
    this.continer.removeChild(this.img);
    this.img = '';
  }

  // 将该区域内内容剪切
  cut2CopyCtx() {
    let [x, y, w, h] = [this.left, this.top, this.continerWidth, this.continerHeight];
    this.global.cutOrCopy(this.ctx, this.copyCtx, {x, y, w, h});
  }
  // 该区域内容删除
  cut() {
    this.copyCtx.fillStyle = this.global.option.backgroundColor;
    this.copyCtx.beginPath();
    this.copyCtx.rect(0,0,this.continerWidth,this.continerHeight);
    this.copyCtx.closePath();
    this.copyCtx.fill();
    this.destroyContiner();
  }
  // todo 系统粘贴有问题
  doPaste() {
    this.global.box.focus();
    setTimeout(_ => {
      this.global.readyCopy();
    }, 1000);
  }
  createByImg(img) {
    let {offsetHeight, offsetWidth, width, height} = img;
    offsetWidth = offsetWidth || width
    offsetHeight = offsetHeight || height
    this.initContiner(0,0,offsetWidth,offsetHeight);
    this.created(img);
  }
  /** 事件监听 */
  onClipbrdEvent(type, img) {
    switch(type) {
      case 'copy':
        this.copy();
        break;
      case 'cut':
        this.cut();
        break;
      case 'paste':
        if (!this.img) {
          this.createByImg(img);
        } else {
          this.paste();
        }
        break;
    }
  }
  onMoveByKey(e) {

  }
}